<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>土分析委托书</title>
    <script src="/libs/jexcel/jexcel.js"></script>
    <script src="/libs/jexcel/jsuites.js"></script>
    <link rel="stylesheet" href="/libs/jexcel/jsuites.css" type="text/css"/>
    <link rel="stylesheet" href="/libs/jexcel/jexcel.css" type="text/css"/>
    <script src="./underscore.js"></script>

    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <style>
        html, body {
            padding: 0;
            margin: 0;
        }

        #set-spreadsheet,
        #my-spreadsheet {
            margin: -2px -2px 20px -2px;
        }

        .sheet-ctner-tool {
            background: #0079c4;
            position: relative;
            border: 1px solid #0079c4;
            margin: 0 auto;
            padding: 10px 20px;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            box-shadow: 0px 2px 3px 0px rgba(0, 0, 0, 0.32);
            z-index: 999999999;
        }

        .sheet-ctner {
            background: #FFF;
            overflow: auto;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #cccccc;
        }

        .btn {
            /*position: absolute;*/
            padding: 7px 9px;
            font-size: 12px;
            border-radius: 4px;
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            background: #fff;
            border: 1px solid #c4c4c4;
            color: #1f2d3d;
            margin: 0;
            text-decoration: none;
        }
    </style>
</head>
<body>
<div class="sheet-ctner-tool">
    <a href="javascript:void(0)" class="btn btn-save" style="left:0px;"
       onclick="test()"

    >保存</a>
    <a href="javascript:void(0)"
       onclick="test(true)"
       class="btn btn-export">导出</a>
    <a href="javascript:void(0)"
       onclick="resetCategory()"
       class="btn btn-reset">重置分类</a>
    <a href="javascript:void(0)"
       onclick="returnBook()"
       class="btn btn-list">返回任务书列表</a>
</div>
<div class="sheet-ctner">

    <div style="padding-bottom:20px;position:relative;">

        <div style="text-align: center;font-size: 24px;margin-bottom: 20px;">土 分 析 委 托 书</div>
        <div style="width:100%;overflow: auto; border: 1px solid #cccccc;">
            <div id='set-spreadsheet'></div>
        </div>
    </div>
    <div style="width:100%;overflow: auto; border: 1px solid #cccccc;">
        <div id='my-spreadsheet'></div>
    </div>
</div>

</body>
<script>
    var domain = location.host;
    // var domain = '1.85.30.164:8821';
    var dateOpt = {
        resetButton: false,
        //format:'YYYY/MM/DD' ,
        // Allow keyboard date entry
        readonly: 0,
        // Today is default
        today: 0,
        // Show timepicker
        time: 0,
        // Show the reset button
        resetButton: true,
        // Placeholder
        placeholder: '请选择日期',
        // Translations can be done here
        months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        weekdays: ['周日', '周一', '周一', '周三', '周四', '周五', '周六'],
        weekdays_short: ['日', '一', '二', '三', '四', '五', '六'],
        // Value
        format: 'YYYY/MM/DD',
        value: null,
        // Events
        onclose: null,
        onchange: null,
        // Fullscreen (this is automatic set for screensize < 800)
        fullscreen: false,
    };

    /**
     * window.location.search to object
     * @returns {{}}
     */

    function parseSearch(search) {
        var resultObj = {};
        var search = search || window.location.search;
        if (search && search.length > 1) {
            var search = search.indexOf('?') == 0 ? search.substring(1) : search;
            var items = search.split('&');
            for (var index = 0; index < items.length; index++) {
                if (!items[index]) {
                    continue;
                }
                var kv = items[index].split('=');
                if (resultObj[kv[0]] != undefined) {
                    if ($.isArray(resultObj[kv[0]])) {
                        // resultObj[kv[0]].push(decodeURI(kv[1])); // 解码
                        resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                    } else {
                        // var ar = [resultObj[kv[0]],decodeURI(kv[1])];
                        resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                    }
                } else {
                    resultObj[kv[0]] = typeof kv[1] === "undefined" ? "" : decodeURI(kv[1]); // 解码
                }
            }
        }
        return resultObj;
    }

    var dataTable, checkers = [], setingTable, headerLine2, headerLine1, settingHeader,
        settingData = [['', '', '', '',]], data1Data;
    var searchObj = parseSearch(location.search);
    var id = searchObj.id, tk = searchObj.tk; //read=1读取已有设置，2单纯读取不能写入


    window.onload = function () {
        if (searchObj.read == 2) {
            $('.btn-save').remove();
            $('.btn-reset').remove();
            $('.btn-list').html('返回');
        }
        // $.get('/api/v1/sample/book/' + id, function (samples) {

        settingHeader = [
            {
                width: 150,
                type: 'calendar',
                title: '委托日期',
                options: dateOpt,
            },
            {
                options: dateOpt,
                width: 150,
                type: 'calendar',
                title: '要求完成日期'
            },
            {
                type: 'dropdown',
                width: 360,
                title: '依据标准',
                source: ['土工试验方法标准（GB/T 50123-2019）', '公路土工试验规程（JTG E40-2007）', '铁路工程土工试验规程（TB 10102-2010）']
            },
            {
                type: 'dropdown',
                title: '审核人',
                width: 100,
                source: ['王工', '戚长军', '苏伟明']
            }
        ];
        $.get('http://' + domain + '/api/v1/category/sampleDetailSum/' + id, function (data, status) {
            var category = data.data['category'],
                book = data.data['book'];
            shuiwei = data.data['shuiwei'];
            checkers = data.data['checkers'].list

            ;

            if (shuiwei && shuiwei.length) {
                // let waterLevel=  shuiwei[0];
                shuiwei = _.groupBy(shuiwei, 'targetId');
            } else {
                shuiwei = {}
            }
            // debugger;
            // console.log("数据: " + data + "\n状态: " + status);
            var columnns = JSON.parse(category.remark2);

            if (searchObj.read) {
                headerLine1 = columnns.header1;
                headerLine2 = columnns.header2;
                data1Data = columnns.datas1;
                // setingTable = columnns.settingHeader;
                settingData = columnns.settingData;
                settingHeader[3].source = checkers.map(user => {
                    // ['王工', '戚长军', '苏伟明']
                    return user.id + user.name;
                });
            } else {
                //
                settingHeader = [
                    {
                        width: 150,
                        type: 'calendar',
                        title: '委托日期',
                        options: dateOpt,
                    },
                    {
                        options: dateOpt,
                        width: 150,
                        type: 'calendar',
                        title: '要求完成日期'
                    },
                    {
                        type: 'dropdown',
                        width: 360,
                        title: '依据标准',
                        source: ['土工试验方法标准（GB/T 50123-2019）', '公路土工试验规程（JTG E40-2007）', '铁路工程土工试验规程（TB 10102-2010）']
                    },
                    {
                        type: 'dropdown',
                        title: '审核人',
                        width: 100,
                        source: checkers.map(user => {
                            return user.id + user.name;
                        })
                    }
                ];
                headerLine1 = [
                    {title: '',},
                    {title: '',},
                    {title: '',},
                    {title: '',},
                    // {title: '取样深度', colspan: 2},
                    {title: '',}
                ], headerLine2 = [
                    {title: '试验室编号', width: 90},
                    {title: '土样编号', width: 90},
                    {title: '取样深度', width: 50},
                    {title: '数量', width: 50},
                    {title: '土的现场定名', width: 120}
                ];
                columnns.map(item => {
                    if (item.children) {
                        item.children.map(ele => {
                            headerLine2.push({
                                title: ele.label,
                                width: (ele.label.length * 20 + 10),
                            });
                        });
                        headerLine1.push({
                            title: item.label,
                            colspan: item.children.length
                        })
                    } else { //
                        headerLine1.push({
                            title: '',
                        });
                        headerLine2.push({
                            title: item.label
                        });//
                    }
                });
                data1Data = [
                    ...book.list.map(function (item) {
                        var item3 = JSON.parse(item.method3);
                        return [
                            '01',
                            item.no,
                            item3.startAt,//深度
                            item3.method4 ? 2 : 1,//
                            item3.remark2,//
                            ...headerLine2.slice(5).map((ele, index) => {
                                if (item.remark3 == '扰动' && (ele.title == '筛分' || ele.title == '黏粒含量')) {
                                    return '√';
                                }
                                if (item.remark3 == '原状') {
                                    if (shuiwei && shuiwei[item.targetId]) {
                                        let waterLevel = shuiwei[item.targetId][0];
                                        //水位以下
                                        if (waterLevel.method2 > item.endAt && (ele.title == '湿陷系数' || ele.title == '自重湿陷系数')) {
                                            return '√';
                                        }

                                    } else if ((ele.title == '湿陷系数' || ele.title == '自重湿陷系数')) {
                                        //勘探点没见水（没输水位）取的原状土样就当是水位以上的也自动勾选湿陷试验和自重湿陷试验
                                        return '√';
                                    }
                                    return (ele.title == '压缩性' || ele.title == '物理指标') ? '√' : '';
                                }
                                return '';
                            })
                        ];
                    }),
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                    ['', '', '', '', '', ...headerLine2.slice(5).map((item, index) => (''))],
                ];
            }

            var data = [
                ['01', 'T09', '0.9'],
            ];


            var internationalText = {
                noRecordsFound: '没有内容',
                showingPage: 'Mostrando página {0} de {1} entradas',
                show: '显示',
                entries: 'entradas',
                insertANewColumnBefore: '列前插入',
                insertANewColumnAfter: '列后插入',
                deleteSelectedColumns: '删除已选列',
                renameThisColumn: '重命名本列',
                orderAscending: '排序',
                orderDescending: '倒序',
                insertANewRowBefore: '行前插入',
                insertANewRowAfter: '行后插入',
                deleteSelectedRows: '删除所选行',
                clearComments: '清楚内容',
                copy: '复制 ...',
                paste: '粘贴 ...',
                saveAs: '另存为',
                about: '关于',
                areYouSureToDeleteTheSelectedRows: '确认删除所选行?',
                areYouSureToDeleteTheSelectedColumns: '确认删除所选列?',
                thisActionWillDestroyAnyExistingMergedCellsAreYouSure: '取消所有合并?',
                thisActionWillClearYourSearchResultsAreYouSure: '清楚所有查询条件?',
                thereIsAConflictWithAnotherMergedCell: '和其他合并有冲突',
                invalidMergeProperties: '无效合并属性',
                cellAlreadyMerged: '单元格已合并',
                noCellsSelected: '没有选择单元格',
            };
            dataTable = jexcel(document.getElementById('my-spreadsheet'), {
                defaultColWidth: 100,
                tableOverflow: true,
                tableWidth: window.innerWidth > 1200 ? (window.innerWidth - 40) : "1200px",
                tableHeight: '1100px',
                includeHeadersOnDownload: false,
                columnSorting: false,
                csvFileName: '试验任务书',
                // fullscreen:true,
                csvHeaders: true,
                style: {background: '#333'},
                allowExport: true,
                data: data1Data,
                editable: searchObj.read == '2' ? false : true,
                text: internationalText,
                columns: headerLine2,
                nestedHeaders: [
                    headerLine1
                ],


            })


            setingTable = jexcel(document.getElementById('set-spreadsheet'), {
                defaultColWidth: 100,
                tableOverflow: true,
                tableWidth: window.innerWidth > 1200 ? (window.innerWidth - 40) : "1200px",
                includeHeadersOnDownload: false,
                columnSorting: false,
                editable: searchObj.read == '2' ? false : true,
                csvHeaders: false,
                // style: {background: '#333'},
                data: settingData,
                text: internationalText,
                columns: settingHeader,

            })

            // });
        });


        document.getElementsByClassName('sheet-ctner')[0].style.width = '1200px';
        document.getElementsByClassName('sheet-ctner-tool')[0].style.width = '1200px';


    };

    function test(isExport) {
        // console.log(dataTable.getData())
        var
            delegateDate = setingTable.getValueFromCoords(0, 0), //委托日期
            finishDate = setingTable.getValueFromCoords(1, 0), //要求完成日期
            standDesc = setingTable.getValueFromCoords(2, 0),//依据标准
            checkPerson = setingTable.getValueFromCoords(3, 0)//审核人
        ;
        if (!delegateDate ||
            !finishDate ||
            !standDesc ||
            !checkPerson
        ) {
            return alert('请完善委托日期、要求完成日期、依据标准、审核人内容')
        }
        // console.log(JSON.stringify({
        //     header1: headerLine1,
        //     header2: headerLine2,
        //     datas1: dataTable.getData(),
        //     // settingHeader:settingData,
        //     settingData: setingTable.getData(),
        // }));
        let checkerObj = {};
        checkers.map(function (item) {
            checkerObj[item.id + item.name] = item;
        });
        $.ajax({
            url: 'http://' + domain + '/api/v1/category/',
            contentType: "application/json",
            type: 'post',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("tk", tk);
            },
            dataType: 'json',
            data: JSON.stringify({
                id: id,
                remark2: JSON.stringify({
                    header1: headerLine1,
                    header2: headerLine2,
                    datas1: dataTable.getData(),
                    // settingHeader:settingData,
                    settingData: setingTable.getData(),
                }),
                pId: checkerObj[setingTable.getData()[0][3]].id
            }),
            success: function (data, status) {
                if (isExport) {
                    window.open('http://' + domain + '/api/v1/category/exportTaskBook?id=' + id, '_blank');
                } else {
                    alert('委托书设置成功')
                }
            }
        });
    }

    //导出
    function exportData() {
        // dataTable.download(true);
        window.open('http://' + domain + '/api/v1/category/exportTaskBook?id=' + id, '_blank');
    }

    //返回至设置任务要求
    function resetCategory() {
        window.parent.location = 'http://' + domain + '/bookSet/' + id + '?r=' + Math.random()
    }

    //返回至任务书列表
    function returnBook() {
        if (searchObj.read == '2') { //返回试验室任务书列表
            window.parent.location = 'http://' + domain + '/trialDetailBook/6/' + id;
        } else {
            window.parent.location = 'http://' + domain + '/book/6';
        }
    }
</script>
</html>
